package net.huashitong.oversee.web;

import com.google.gson.annotations.Until;
import com.sirdc.modules.core.web.JsonBaseController;
import com.sirdc.modules.core.web.model.JqGrid;
import com.sirdc.modules.core.web.model.Message;
import com.sirdc.modules.sys.util.MD5;
import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;
import net.huashitong.Project.responseModel.MailListDataModel;
import net.huashitong.Project.util.MessageUtil;
import net.huashitong.node.filter.NodeNewschedulesFilter;
import net.huashitong.node.service.NodeNewschedulesService;
import net.huashitong.oversee.entity.Coordinate;
import net.huashitong.oversee.entity.GradePoint;
import net.huashitong.oversee.entity.SupervisionTask;
import net.huashitong.oversee.filter.CoordinateFilter;
import net.huashitong.oversee.filter.GradePointFilter;
import net.huashitong.oversee.filter.SupervisionTaskFilter;
import net.huashitong.oversee.service.CoordinateService;
import net.huashitong.oversee.service.FeedBackLeaderService;
import net.huashitong.oversee.service.SupervisionTaskService;
import net.huashitong.taskGroup.entity.DeptList;
import net.huashitong.taskGroup.entity.JobGroup;
import net.huashitong.taskGroup.service.DeptListService;
import net.huashitong.taskGroup.service.JobGroupService;
import net.huashitong.user.databean.BnpUserDatabean;
import net.huashitong.user.entity.BnpUser;
import net.huashitong.user.filter.BnpUserFilter;
import net.huashitong.user.service.BnpUserService;
import net.huashitong.utils.UtilsTools;
import org.apache.http.HttpRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.util.*;

@Controller
@RequestMapping("/qestionReport")
public class QuestionReport extends JsonBaseController {

    Logger log = LoggerFactory.getLogger(QuestionReport.class);
    @Autowired
    private BnpUserService bs;
    @Autowired
    private SupervisionTaskService supervisionTaskService;
    @Autowired
    private CoordinateService coordinateService;
    @Autowired
    private DeptListService deptListService;
    @Autowired
    private JobGroupService jobGroupService;
    @Autowired
    private NodeNewschedulesService ns;
    @Autowired
    private FeedBackLeaderService feedservice;
    @Autowired
    private BnpUserService bnpUserService;
    @Autowired
    private MessageUtil mu;

    @Override
    protected String getView(String s) {
        return "/modules/question/" + s;
    }

    @RequestMapping(method = RequestMethod.GET)
    public String initPage(HttpServletRequest request, Model model) {
        model.addAttribute("leftType", "提请协调");
        BnpUser bnpUser = (BnpUser) WebUtils.getSessionAttribute(request, "user");
        if (ObjectUtils.isBlank(bnpUser)) {
            return "/modules/login/login";
        }
        //待办任务个数
        int nodeCount = (int) WebUtils.getSessionAttribute(request, "nodeCount");
        model.addAttribute("nodeCount", nodeCount);

        model.addAttribute("user", bnpUser);

        //我的协调
        CoordinateFilter coordinateFilter = new CoordinateFilter();
        coordinateFilter.setUserinfo(bnpUser.getPhone());
        coordinateFilter.setBranchType(bnpUser.getBranchType()); //设置查询权限
        if (StringUtils.isBlank(coordinateFilter.getGroupCode())) //督查组权限
        {
            coordinateFilter.setGroupCode(bnpUser.getGroupCode());
        }
        int quetionNum = coordinateService.queryCoordinateCount(coordinateFilter);
        model.addAttribute("quetionNum", quetionNum);
        WebUtils.setSessionAttribute(request, "quetionNum", quetionNum);

        int myTaskNum = (int) WebUtils.getSessionAttribute(request, "myTaskNum");
        model.addAttribute("myTaskNum", myTaskNum);

        //攻坚任务
        SupervisionTaskFilter taskFilter1 = new SupervisionTaskFilter();
        taskFilter1.setUserinfo(bnpUser.getPhone());
        taskFilter1.setBranchType(bnpUser.getBranchType());
        taskFilter1.setRole(bnpUser.getRole());
        taskFilter1.setValid("1");
        taskFilter1.setTackFlag("1");
        int myTackTaskNum = supervisionTaskService.getMissinTaskCount(taskFilter1);
        WebUtils.setSessionAttribute(request, "myTackTaskNum", myTackTaskNum);
        model.addAttribute("myTackTaskNum", myTackTaskNum);

        return getView("query");
    }

    //初始化搜索框
    @RequestMapping("/filter")
    public String filter(@ModelAttribute CoordinateFilter filter) {
        return getView("filter");
    }

    @ResponseBody//初始化
    @RequestMapping(method = RequestMethod.POST)
    public JqGrid query(@ModelAttribute CoordinateFilter filter, HttpServletRequest request) {
        BnpUser bnpUser = (BnpUser) WebUtils.getSessionAttribute(request, "user");

        filter.setUserinfo(bnpUser.getPhone());
        filter.setBranchType(bnpUser.getBranchType()); //Set query permission
        if (StringUtils.isBlank(filter.getGroupCode())) //督查组权限
        {
            filter.setGroupCode(bnpUser.getGroupCode());
        }
        List<Coordinate> lists = coordinateService.queryCoordinate(filter);
        return coverJqGrid(filter, lists);
    }


    //----------------申请协调---------------
    @ResponseBody
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public Message create(@ModelAttribute CoordinateFilter filter, HttpServletResponse response, HttpServletRequest request) {
        BnpUser user = (BnpUser) WebUtils.getSessionAttribute(request, "user");
        String username = user.getName();
        filter.setUserId(user.getSysId());
        filter.setReportUser(username);
        filter.setReportTime(UtilsTools.getCurrentDateTime());
        Coordinate coordinate = new Coordinate();
        BeanUtils.copyProperties(filter, coordinate);
        coordinate.setAaa001("1");//1 有效。

        coordinateService.save(coordinate);
        String msg = "【重大项目节点管理】您好,项目:<" + coordinate.getProjectName() + ">新增一条需协调事项,协调事项为:<" + coordinate.getHelpInfo() + ">请登录查看详情,并及时处理。系统地址：https://www.fzzhengxinyun.com ，帐号为个人手机号，初始密码123456";
        msg = msg.replace("政府", "");
        msg = msg.replace("逾期", "超期");
        int code = 99;
        //责任人号码
        code = feedservice.QuesttionSendMsg(msg, coordinate.getResUserPhone());
        if (0 == code) log.info("---责任人发送成功 ---");
        //负责人号码
        feedservice.QuesttionSendMsg(msg, coordinate.getBossPhone());
        if (0 == code) log.info("---负责人发送成功 ---");
        //经办人
        feedservice.QuesttionSendMsg(msg, coordinate.getOperatorPhone());
        if (0 == code) log.info("---经办人发送成功 ---");
        //分管县领导
        feedservice.QuesttionSendMsg(msg, coordinate.getfGcountyLeaderPhone());
        log.info("---分管县领导发送成功 ---");

        return coverMessage("200");
    }

    /**
     * 申请协调
     *
     * @param model
     * @return url
     */
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public String showAddView(@ModelAttribute CoordinateFilter filter, Model model, HttpServletRequest request) {
        filter.setReportTime(UtilsTools.getCurrentDate());
        BnpUser user = (BnpUser) WebUtils.getSessionAttribute(request, "user");
        String username = user.getName();

        //涉及单位（involveUnit）
        List<BnpUserDatabean> deptLists = coordinateService.queryAllInvolveUnit();

        model.addAttribute("reportUser", username);
        model.addAttribute("deptLists", deptLists);
        model.addAttribute("coordinate", filter);
        return getView("applyForm");
    }

    /**
     * 问题转批（显示）
     *
     * @param model
     * @param id
     * @return
     */
    @RequestMapping(value = "/edit1/{id}", method = RequestMethod.GET)
    public String showEditView1(Model model, @PathVariable String id, HttpServletRequest request) throws ParseException {
        Coordinate coordinate = coordinateService.getById(id);
        List<SupervisionTask> list = new ArrayList<>();
        if (StringUtils.isNotBlank(coordinate.getNodeSysId())) {
            SupervisionTaskFilter taskFilter = new SupervisionTaskFilter();
            taskFilter.setNodeSysId(coordinate.getNodeSysId());
            list = supervisionTaskService.querySupervisionTaskByFilter(taskFilter);
        }
        SupervisionTask task = new SupervisionTask();
        if (ObjectUtils.isNotBlank(list) && list.size() > 0) {
            task.setTaskName(list.get(0).getTaskName());
            task.setTaskContent(list.get(0).getTaskContent());
        } else {
            task.setTaskName("");
            task.setTaskContent("");
        }

        List<JobGroup> jobGroups = jobGroupService.query();
        model.addAttribute("jobGroups", jobGroups);
        String startDate = UtilsTools.getCurrentDate();
        model.addAttribute("startDate", startDate);
        String endDate = UtilsTools.plusDay(10, startDate);
        model.addAttribute("endDate", endDate);
        model.addAttribute("coordinate", coordinate);
        model.addAttribute("task", task);
        //return getView("creatTask1");
        return getView("questionTurnForm");
    }


    /**
     * 问题转批（生成攻坚督查）
     *
     * @param
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/edit1", method = RequestMethod.POST)
    public Message update1(@ModelAttribute CoordinateFilter filter, HttpServletRequest request) {

        Coordinate coor = coordinateService.getById(filter.getSysId());
        if ("2".equals(coor.getAaa001())) {
            return coverMessage("500", "批转失败,您所选择的协调事项已经转为督查任务，不能重复批转");
        }

        List<SupervisionTask> list = new ArrayList<>();
        if (StringUtils.isNotBlank(coor.getNodeSysId())) {
            SupervisionTaskFilter taskFilter = new SupervisionTaskFilter();
            taskFilter.setNodeSysId(coor.getNodeSysId());
            list = supervisionTaskService.querySupervisionTaskByFilter(taskFilter);
        }

        String sysid = supervisionTaskService.saveAutoTaskJob(filter, list);
        // 转为攻坚督查
        coor.setAaa001("2");
        coordinateService.update(coor);
        //通知县分管领导
        if (StringUtils.isNotBlank(coor.getfGcountyLeaderPhone()) && StringUtils.isNotBlank(coor.getfGcountyLeader())) {
            mu.sendTackMessageToFGLeader(coor);
        }


        //保存到督查系统
//        supervisionTaskService.saveTasktoDuCha(sysid);
        return coverMessage("200");
    }


    //问题修改
    @RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
    public String showEditView(Model model, @PathVariable String id, HttpServletRequest request) {
        Coordinate coordinate = coordinateService.getById(id);
        BnpUser user = (BnpUser) WebUtils.getSessionAttribute(request, "user");
        String username = user.getName();
        model.addAttribute("reportUser", username);

        //涉及单位（involveUnit）
        List<BnpUserDatabean> deptLists = coordinateService.queryAllInvolveUnit();

        String involveUnitsStr = coordinate.getInvolveUnit();
        String[] invArr = involveUnitsStr.split(",");
        List<String> involveUnitsList = Arrays.asList(invArr);
        List<String> check = new ArrayList<>();
        for (BnpUserDatabean dept : deptLists) {
            boolean flag = false;
            for (String involve : involveUnitsList) {
                if (involve.equals(dept.getBranch())) {
                    flag = true;
                    break;
                }
            }
            if (flag) {
                dept.setBranchType("selected");
            } else {
                dept.setBranchType("noSelected");
            }
        }

        model.addAttribute("deptLists", deptLists);
        model.addAttribute("coordinate", coordinate);
        return getView("questionUpdateForm");
    }

    @ResponseBody
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public Message update(@ModelAttribute CoordinateFilter filter, HttpServletRequest request) {

        Coordinate coord = coordinateService.getById(filter.getSysId());
        if (ObjectUtils.isBlank(coord)) {
            return coverMessage("500", " 找不到该记录,请联系管理员");
        }
        BnpUser user = (BnpUser) WebUtils.getSessionAttribute(request, "user");
        filter.setReportTime(coord.getReportTime());
        String username = user.getName();
        filter.setUserId(user.getSysId());
        filter.setReportUser(username);
        BeanUtils.copyProperties(filter, coord);
        coordinateService.update(coord);
        return coverMessage("200");
    }

    @RequestMapping(value = "/detail/{id}", method = RequestMethod.GET)
    public String detail(Model model, @PathVariable String id, HttpServletRequest request) {
        Coordinate coordinate = coordinateService.getById(id);
        BnpUser user = (BnpUser) WebUtils.getSessionAttribute(request, "user");
        String username = user.getName();
        model.addAttribute("reportUser", username);
        //涉及单位（involveUnit）
        List<BnpUserDatabean> deptLists = coordinateService.queryAllInvolveUnit();
        String involveUnitsStr = coordinate.getInvolveUnit();
        String[] invArr = involveUnitsStr.split(",");
        List<String> involveUnitsList = Arrays.asList(invArr);
        List<String> check = new ArrayList<>();
        for (BnpUserDatabean dept : deptLists) {
            boolean flag = false;
            for (String involve : involveUnitsList) {
                if (involve.equals(dept.getBranch())) {
                    flag = true;
                    break;
                }
            }
            if (flag) {
                dept.setBranchType("selected");
            } else {
                dept.setBranchType("noSelected");
            }
        }

        model.addAttribute("deptLists", deptLists);
        model.addAttribute("coordinate", coordinate);
        return getView("detail");
    }

    /**
     * 设置成处理完毕
     *
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/cancelProblem/{id}")
    public Message cancelProblem(@PathVariable List<String> id) {
        List<Coordinate> coordinates = new ArrayList<>();
        for (String str : id) {
            Coordinate coordinate = coordinateService.getById(str);
            coordinate.setAaa001("3");
            coordinates.add(coordinate);
        }
        coordinateService.batchUpdate(coordinates);
        return coverMessage("200");
    }


    /**
     * 撤销协调
     *
     * @param model
     * @param id
     * @return
     */
    @RequestMapping(value = "/revoke/{id}", method = RequestMethod.GET)
    public String showAddProblem(Model model, @PathVariable String id) {
        Coordinate coordinate = coordinateService.getById(id);
        model.addAttribute("problem", coordinate);
        return getView("revoke");
    }

    @ResponseBody
    @RequestMapping(value = "/revoke", method = RequestMethod.POST)
    public Message addProblem(@ModelAttribute CoordinateFilter filter, HttpServletRequest request, Model model) {
        String sysId = filter.getSysId();
        Coordinate coordinate = coordinateService.getById(sysId);
        if (ObjectUtils.isNotBlank(coordinate)) {
            //撤销协调
            coordinate.setAaa001("0");
            coordinate.setRevokeReason(filter.getRevokeReason());   //撤销原因
            if (StringUtils.isNotBlank(coordinate.getNodeSysId())) {
                //验证是否已有相关问题，有的话则撤销督查任务任务中的攻坚任务标志
                SupervisionTaskFilter taskFilter = new SupervisionTaskFilter();
                taskFilter.setNodeSysId(coordinate.getNodeSysId());
                List<SupervisionTask> supervisionTasks = supervisionTaskService.getTaskListsNoPage(taskFilter);

                if (ObjectUtils.isNotBlank(supervisionTasks) && supervisionTasks.size() > 0) {
                    for (SupervisionTask sup : supervisionTasks) {
                        sup.setTackFlag(null);
                    }
                    supervisionTaskService.batchUpdate(supervisionTasks);
                }
            } else {
                return coverMessage("201", "内部出错");
            }
        } else {
            return coverMessage("201", "内部出错");
        }
        coordinateService.update(coordinate);
        return coverMessage("200");
    }
}
